package com.ruoyi.gateway.utils;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.common.core.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class ThirdAuthCheckUtil {

    @Value("#{${third-perms}}")
    private Map<String, String> perms;

    private Map<String, String> pathPermMap = new HashMap<>();

    @PostConstruct
    private void initPerms() {
        if (MapUtils.isNotEmpty(perms)) {
            for (Map.Entry<String, String> entry : perms.entrySet()) {
                String newKey = entry.getKey().replaceAll("\\*", ".*");
                if (newKey.endsWith("/")) {
                    newKey = newKey.substring(0, newKey.length() - 1);
                }
                pathPermMap.put(newKey, entry.getValue());
            }
        }
    }

    public void checkAuth() {
        String perm = getThirdPerm();
        if (StringUtils.isNotBlank(perm)) {
            StpUtil.checkPermission(perm);
        }
    }

    private String getThirdPerm() {
        SaRequest request = SaHolder.getRequest();
        String path = request.getRequestPath();
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        if (MapUtils.isNotEmpty(pathPermMap)) {
            for (Map.Entry<String, String> entry : pathPermMap.entrySet()) {
                Pattern pattern = Pattern.compile(entry.getKey());
                if (pattern.matcher(path).matches()) {
                    return entry.getValue();
                }
            }
        }
        return null;
    }
}
